package org.demo.db.xsd;

import java.io.File;
import java.io.FilenameFilter;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * 自定义 class loader
 * @author  
 * @date    2010-9-1
 * @file    org.gen.util.DbClassLoader.java
 */
public class DbClassLoader extends URLClassLoader{
	/**
	 * 构造函数
	 * @param dir
	 */
	public DbClassLoader(String dir){
		super(getUrls(dir));
	}

	/**
	 * 获取 dir 目录下的所有 jar
	 * @param lib dir
	 */
	private static URL[] getUrls(String dir){
		URL[] urls = null;
		// get all .jar file
		File lib = new File(dir);
		File[] jars = lib.listFiles(new FilenameFilter(){
			public boolean accept(File dir, String name) {
				if (name.endsWith(".jar")){
					return true;
				}
				return false;
			}
		});
		urls = new URL[jars.length + 1];
		for (int i=0;i<jars.length;i++){
			try {
				urls[i] = jars[i].toURI().toURL();
			} catch (Exception e){
				System.out.println(jars[i] + " can't convert to url");
			}
		}
		try {
			urls[urls.length -1] = lib.toURI().toURL();
		} catch (Exception e){
			System.out.println(lib + " can't convert to url");
		}
		return urls;
	}
	/**
	 * 添加 urls
	 * @param urls
	 */
	public void addUrls(URL[] urls){
		if (urls == null){
			return;
		}
		for(int i=0;i<urls.length;i++){
			super.addURL(urls[i]);
		}
	}
}
